package com.etc.security.service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.etc.security.dao.UserRepository;
import com.etc.security.domain.JwtUser;
import com.etc.security.po.AdminMst;

/**
 * Created by echisan on 2018/6/23
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        List<Map> mlist = userRepository.findByPhone(s);

        //如果通过用户名找不到用户，则抛出UsernameNotFoundException异常
        if (CollectionUtils.isEmpty(mlist)) {
            throw new UsernameNotFoundException("没有用户名");
        }
        AdminMst user = new AdminMst();
        Map m = new HashMap();
        for (Map n: mlist) {
            user = new AdminMst();
            String rn = String.valueOf(n.get("rname"));
            if (!m.containsKey(rn)) {
                m.put(rn, Collections.singleton(""));
                user.setRoles(rn);
                user.setPassword(String.valueOf(n.get("psd")));
                user.setUsername(String.valueOf(n.get("phone")));
                return new JwtUser(user);
            }
        }
       
        
        return new JwtUser(user);
    }

}
